<template>
  <a-modal v-model:visible="visible" :title="title" :mask-closable="false" :esc-to-close="false"
    :width="width >= 600 ? 600 : '100%'" draggable @before-ok="save" @close="reset">
    <GiForm ref="formRef" v-model="form" :columns="columns" />
  </a-modal>
</template>

<script setup lang="ts">
  import { Message } from '@arco-design/web-vue'
  import { useWindowSize } from '@vueuse/core'
  import { getPartRecords, addPartRecords, updatePartRecords } from '@/apis/asset/part/records'
  import { type ColumnItem, GiForm } from '@/components/GiForm'
  import { useResetReactive } from '@/hooks'
  import { useDict } from '@/hooks/app'

  import { producer } from '@/hooks/asset'
  import { partCategory } from '@/hooks/asset'
  import { depreacitionRules } from '@/hooks/asset'

  const emit = defineEmits < {
  (e: 'save-success'): void
}> ()

  const { width } = useWindowSize()

  const dataId = ref('')
  const visible = ref(false)
  const isUpdate = computed(() => !!dataId.value)
  const title = computed(() => (isUpdate.value ? '修改配件' : '新增配件'))
  const formRef = ref < InstanceType < typeof GiForm >> ()

  const { producerList, getProducerList } = producer()
  const { partCategoryList, getPartCategoryList } = partCategory()
  const { depreacitionRulesList, getDepreacitionRules } = depreacitionRules()

  const [form, resetForm] = useResetReactive({
    // todo 待补充
  })

  const columns: ColumnItem[] = reactive([
    {
      label: '编号',
      field: 'code',
      type: 'input',
      span: 24,
      required: true,
      props: {
        maxLength: 50,
      },
    },
    {
      label: '名称',
      field: 'name',
      type: 'input',
      span: 24,
      required: true,
      props: {
        maxLength: 100,
      },
    },
    {
      label: '类型',
      field: 'categoryId',
      type: 'tree-select',
      span: 24,
      required: true,
      props: {
        data: partCategoryList,
        allowClear: true,
        allowSearch: true,
        fallbackOption: false,
        filterTreeNode(searchKey: string, nodeData: TreeNodeData) {
          if (nodeData.title) {
            return nodeData.title.toLowerCase().includes(searchKey.toLowerCase())
          }
          return false
        },
      },
    },

    {
      label: '供应商',
      field: 'producerId',
      type: 'select',
      span: 24,
      required: true,
      props: {
        options: producerList,
        placeholder: "请选择供应商",
        allowClear: true,
        allowSearch: true,
      }
    },
    {
      label: '规格',
      field: 'specification',
      type: 'input',
      span: 24,
      props: {
        maxLength: 50,
      },
    },
    {
      label: '序列号',
      field: 'sn',
      type: 'input',
      span: 24,
      props: {
        maxLength: 50,
      },
    },
    {
      label: '单价',
      field: 'price',
      type: 'input',
      span: 24,
    },
    {
      label: '购买日期',
      field: 'purchaseDate',
      type: 'date-picker',
      span: 24,
    },
    {
      label: '过保日期',
      field: 'expireDate',
      type: 'date-picker',
      span: 24,
    },
    {
      label: '折旧规则',
      field: 'depreciationRuleId',
      type: 'select',
      span: 24,
      props: {
        options: depreacitionRulesList,
        placeholder: "请选择",
        allowClear: true,
        allowSearch: true,
        allowCreate: true
      }
    },
  ])

  // 重置
  const reset = () => {
    formRef.value?.formRef?.resetFields()
    resetForm()
  }

  // 保存
  const save = async () => {
    try {
      const isInvalid = await formRef.value?.formRef?.validate()
      if (isInvalid) return false
      if (isUpdate.value) {
        await updatePartRecords(form, dataId.value)
        Message.success('修改成功')
      } else {
        await addPartRecords(form)
        Message.success('新增成功')
      }
      emit('save-success')
      return true
    } catch (error) {
      return false
    }
  }

  // 新增
  const onAdd = async () => {
    reset()
    await getPartCategoryList()
    await getProducerList()
    await getDepreacitionRules()
    dataId.value = ''
    visible.value = true
  }

  // 修改
  const onUpdate = async (id: string) => {
    reset()
    await getPartCategoryList()
    await getProducerList()
    await getDepreacitionRules()
    dataId.value = id
    const { data } = await getPartRecords(id)
    Object.assign(form, data)
    visible.value = true
  }

  defineExpose({ onAdd, onUpdate })
</script>

<style scoped lang="scss"></style>